var express = require('express');
const router = express.Router();
const shortid = require('shortid')
const lowdb = require('lowdb')
const Filesync = require('lowdb/adapters/FileSync');
const adapter = new Filesync(__dirname + '/../data/db.json');
const db = lowdb(adapter);
var mysql = require('mysql');
const { error } = require('console');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'lwmy4ever..0',
  database: 'shujuku'
});

connection.connect();

/* GET home page. */
router.get('/account', function (req, res, next) {

  //let data = db.get('accounts').value();
  let sql = `select * from records`;
  connection.query(sql, (error, result) => {
    if (error) {
      console.log(error);
      return;
    }
    else {
      res.render('account', { accounts: result, url: req.url + '/create' });
    }
  });


});


//删除id请求
router.get('/account/create/:id', function (req, res, next) {
  let data = req.params.id;
  let sql = `delete from records where id = '${data}'`;
  connection.query(sql);
  console.log(data);
  res.render('success', { msg: '删除成功', url: '/account' });
});


router.get('/account/create', function (req, res, next) {
  res.render('create');
});



//提交添加请求
router.post('/account', (req, res) => {
  console.log(req.body);
  let id = shortid.generate();
  const resu = { id: id, ...req.body }
  let sql = `INSERT INTO records SET ?`;
  connection.query(sql, resu);
  res.render('success', { msg: '添加成功', url: req.url });
})

module.exports = router;
